#!/bin/bash
### BEGIN INIT INFO
# Provides:          alfresco_repo
# Required-Start:    $remote_fs $network $syslog $mysql
# Required-Stop:     $remote_fs $network $syslog $mysql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Alfresco Repository Service
### END INIT INFO

#
# Alfresco repo control script
# http://www.craigburke.com/blog/2011/08/25/setting-up-tomcat-on-ubuntu/
#
# chkconfig:
# description:  Start up the Tomcat servlet engine.
 
# Source function library.
# /etc/init.d/functions
 
export CATALINA_HOME="/opt/alfresco/tomcat"
 
TOMCAT_USER='alfresco'
SHUTDOWN_WAIT=20
 
tomcat_pid() {
  echo `ps aux | grep $CATALINA_HOME | grep catalina | grep -v grep | awk '{ print $2 }'`
}
 
start() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ]
     then
        echo "Tomcat is already running (pid: $pid)"
     else
        echo "Starting Tomcat"
        cd /opt/alfresco/logs
        export JAVA_OPTS="${JAVA_OPTS} -Djava.rmi.server.hostname=alfresco";
        export JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote";
        export JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote.port=8004";
        export JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote.ssl=false";
        export JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote.authenticate=true";
        export JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote.password.file=/opt/alfresco/jmx/jmxremote.password";
        export JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote.access.file=/opt/alfresco/jmx/jmxremote.access";
        /bin/su $TOMCAT_USER $CATALINA_HOME/bin/startup.sh
        cd $OLDPWD
   fi
 
   return 0
}
stop() {
 pid=$(tomcat_pid)
  if [ -n "$pid" ]
  then
 
  echo "Stoping Tomcat"
        /bin/su $TOMCAT_USER $CATALINA_HOME/bin/shutdown.sh 
   echo -n "Waiting for processes to exit ["
   let kwait=$SHUTDOWN_WAIT
    count=0;
    until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
    do
      echo -n ".";
      sleep 1
      let count=$count+1;
    done
    echo "Done]"
 
    if [ $count -gt $kwait ]
    then
      echo "Killing processes ($pid) which didn't stop after $SHUTDOWN_WAIT seconds"
      kill -9 $pid
    fi
  else
    echo "Tomcat is not running"
  fi
 
  return 0
}
 
status() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ]
  then
    echo "Tomcat is running with pid: $pid"
  else
    echo "Tomcat is not running"
  fi
}

case "$1" in
 start)
        start
        ;;
 stop)
        stop
        ;;
 restart|force-reload|reload)
       stop
       start
       ;;
 status)
       status
       ;;
*)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac
exit 0

